import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gongge/utils/AudioUtils.dart';
import 'package:sqflite/utils/utils.dart';
import '../bean/BadgeBean.dart';
import '../game/block.dart';
import '../bean/BlockBean.dart';
import '../utils/WidthUtils.dart';
import 'dart:collection';
import '../bean/Challenge.dart';
import '../bean/GemBean.dart';
import '../config/AppConst.dart';
import '../main.dart';
import '../pages/HomePage.dart';
import '../sqflite/DBManager.dart';
import '../wight/GameEndText.dart';
import '../wight/GameFileText.dart';
import '../wight/My.dart';
import '../wight/TravelGameEnd.dart';
import '../wight/TravelGameFile.dart';
import 'SpUtils.dart';
import '../generated/l10n.dart';
import 'TimeUtils.dart';
import 'dart:math' as math;

class Coordinate {
  int x = 0;
  int y = 0;
  String img = '';
}

class GamePageUtils {
//旅行模式模式排列
  List<List<BlockBean>> setTravelGem(
      List<List<BlockBean>> data, List<GemBean> gemList) {
    List<List<BlockBean>> _data = data;

    //String key =x+y
    HashMap<String, Coordinate> benamap = HashMap();
    for (int i = 0; i < gemList.length; i++) {
      var x = math.Random().nextInt(GAME_PAD_MATRIX_H);
      var y = math.Random().nextInt(GAME_PAD_MATRIX_W ~/ 2);
      if (benamap['$x$y'] != null) {
        //随机值重复了，重新取值
        while (true) {
          y = math.Random().nextInt(GAME_PAD_MATRIX_W ~/ 2);
          if (benamap['$x$y'] == null) {
            print("跳出循环 ");
            break;
          }
        }
      }
      var coordinate = Coordinate();
      coordinate.x = x;
      coordinate.y = y;
      coordinate.img = gemList[i].img;
      benamap['$x$y'] = coordinate;
      _data[x][y].img = gemList[i].img;
      _data[x][y].normal = 1;
      _data[x][y].gem = i + 1;
    }
    //右边再排序
    int i = 0;
    benamap.forEach((key, value) {
      var y = GAME_PAD_MATRIX_W - 1 - value.y;
      _data[value.x][y].gem = i + 1;
      _data[value.x][y].normal = 1;
      i++;
      _data[value.x][y].img = value.img;
    });

    return _data;
  }

  //挑战模式宝石再棋盘上的排列
  List<List<BlockBean>> setGem(List<List<BlockBean>> data, int? currentScore) {
    List<List<BlockBean>> _data = data;
    map.clear();
    var currentScore2 = (currentScore! * 0.6).toInt();
    //print("总宝石=${currentScore},60%=${currentScore2}");

    if (currentScore2 % 2 == 1) {
      //奇数的话,最中心来个宝石
      _data[GAME_PAD_MATRIX_H ~/ 2][GAME_PAD_MATRIX_W ~/ 2].img =
          evearyGem[TimeUtils.CurrentMonth()];
      _data[GAME_PAD_MATRIX_H ~/ 2][GAME_PAD_MATRIX_W ~/ 2].normal = 1;
      _data[GAME_PAD_MATRIX_H ~/ 2][GAME_PAD_MATRIX_W ~/ 2].gem = 1;
      //其他对称排列
      //这里一定是偶数
      var currentScore3 = (currentScore2 - 1) ~/ 2;
      _data = _gemLeft(_data, currentScore3, 1);
      _data = _gemRight(_data, 7);
    } else {
      var currentScore3 = currentScore2 ~/ 2;
      _data = _gemLeft(_data, currentScore3, 1);
      _data = _gemRight(_data, 7);
    }

    return _data;
  }

/**
 * 宝石再棋盘上左手边的排列
 */
  HashMap<int, int> map = HashMap();
  List<List<BlockBean>> _gemLeft(List<List<BlockBean>> _data, int cout, int y) {
    for (int i = 0; i < cout; i++) {
      //宝石再横排随机排列  竖排位置写死的
      var x = math.Random().nextInt(GAME_PAD_MATRIX_W);
      if (map[x] != null) {
        if (map[x] == x) {
          // print("重复了[x]");
          //随机值重复了，重新取值
          while (true) {
            x = math.Random().nextInt(GAME_PAD_MATRIX_W);
            if (map[x] != x) {
              break;
            }
          }
        }
      }
      map[x] = x;
      _data[x][y].img = evearyGem[TimeUtils.CurrentMonth()];
      _data[x][y].normal = 1;
      _data[x][y].gem = 1;
    }

    return _data;
  }

  /**
 * 宝石再棋盘上右边的排列
 */
  List<List<BlockBean>> _gemRight(List<List<BlockBean>> _data, int y) {
    //左右两边相等数量 因为这里一定偶数
    map.forEach((key, value) {
      _data[value][y].img = evearyGem[TimeUtils.CurrentMonth()];
      _data[value][y].normal = 1;
      _data[value][y].gem = 1;
    });

    return _data;
  }

/**
 * 底部棋盘背景图片
 */
  Widget getCheckBooton(double hight) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
          height:hight*0.15,
          margin: EdgeInsets.only(
            top: hight * 0.02,
          ),
          decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage('assets/images/checkerboard_bottom.png'),
                fit: BoxFit.fill),
          )),
      // child: Image.asset(
      //     'assets/images/checkerboard_bottom.png',
      //     fit: BoxFit.contain),
    );
  }

  static saveSore(int currentScore, {int historySore = 0}) {
    SpUtils.getInstance()?.setInt(AppConst.continueScore, currentScore);
  }

  //查询剩下的随机木块是否还有格子填充
  static HashMap<int, int> qruey(List<Block> randowList,
      List<List<BlockBean>> data, HashMap<int, String> rondowRemowMap) {
    //无法填充的随机木块，int随机木块的索引
    HashMap<int, int> hashmap = HashMap();
    bool isFlu = false; //满足填充

    for (int index = 0; index < randowList.length; index++) {
      if (rondowRemowMap[index] == null) {
        //下方拖动方块还在方块
        for (int i = 0; i < data.length; i++) {
          for (int y = 0; y < data[i].length; y++) {
            // 不判断是否满足填充，否则逻辑错误
            //  if(data[i][y].normal!=1){
            isFlu = _judge(randowList[index].shape, i, y, data, index);
            //  }

            if (isFlu) {
              break;
            }
          } //棋盘内循环
          if (isFlu) {
            break;
          }
        } //棋盘外循环
        if (!isFlu) {
          hashmap[index] = index;
        }
      }
    } //随机木块循环

    // hashmap.forEach((key, value) {
    //   print("不满足填充条件的是${key}");
    // });

    return hashmap;
  }

  static bool _judge(List<List<BlockBean>> currentlist, int x, int y,
      List<List<BlockBean>> data, int index) {
    //   bool isBack = false;
    bool isFlu = false; //满足填充

    // int normalCount = 0; //拖动的木块数量
    for (int i = 0; i < currentlist.length; i++) {
      for (int j = 0; j < currentlist[i].length; j++) {
        //这里可能是1，或者2，当等于2时，证明上次不满足填充会变成2
        if (currentlist[i][j].normal != 0) {
          // normalCount = normalCount + 1;
          //当前拖动的方块
          int newx = x + i; //X拖动木块的最左边所在索引
          int newy = y + j; //Y拖动木块的最上边所在索引

          if (newx < GAME_PAD_MATRIX_H && newy < GAME_PAD_MATRIX_W) {
            BlockBean dataBean = data[newx][newy];
            if (dataBean.normal != 1) {
              //此拖动的方块对应棋盘恰好有空位置，
              isFlu = true;
              //   print(  "满足填充newxXXXXXXXXX:${newx},${newy},方块的填充位置X:${i},${j},这是随机方块第${index + 1}个}");
            } else {
              //   print("不满足newxXXXXXXXXX:${newx},${newy},这是随机方块第${index + 1}个}");
              isFlu = false;
              //此拖动的方块对应棋盘恰好有木块了，就不满足填充，退出此拖动方块，继续下一个棋盘寻找，
              break;
            }
          } else {
            isFlu = false;
            break;
          }
        }
      }

      if (!isFlu) {
        break;
      }
    } //外循环

    // print("此木块${index}，满足吗?${isFlu}");

    return isFlu;
  }

  /**
   * 结束游戏 
   */
  void endGame(BuildContext context, int CurrentScore, int HistoricalScore,
      GlobalKey rootWidgetKey, int type,
      {CallBack? callbacks}) {
    AudioUtils?.getInstance()?.pause();
    List<String> lists = [];
    if (type == 1) {
      //经典
      lists.add(S.of(context).no_spaces_left);
      SpUtils?.getInstance()?.setInt(AppConst.continueScore, 0);
      SpUtils?.getInstance()?.setString(AppConst.randomList, "");
      SpUtils.getInstance()!.setString(AppConst.continueGame, "");
    } else if (type == 2) {
      lists.add(S.of(context).finish_gem);
      //成功完成游戏每日挑战
      SpUtils?.getInstance()?.setInt(AppConst.everyDayContinueScore, 0);
      SpUtils?.getInstance()?.setString(AppConst.everyDayrandomList, "");
      SpUtils.getInstance()!.setString(AppConst.everyDayContinueGame, "");
      SpUtils.getInstance()?.setBool(AppConst.complete, true);
      var millisecondsSinceEpoch = DateTime.now().millisecondsSinceEpoch;
      SpUtils.getInstance()
          ?.setInt(AppConst.completeTime, millisecondsSinceEpoch);
      //存当月日期
      var challenge = Challenge();
      challenge.time = millisecondsSinceEpoch;
      challenge.type = 2;
      DBManager().insertChallenge(challenge);
    }
    DBManager().deletaHashModelAll(type);
    print("游戏结束");
    showDialog(
        context: context,
        // barrierColor: Colors.grey.withOpacity(.4), // Dialog 的背景色
        barrierDismissible: false, //控制 Dialog 是否消失
        barrierLabel: "",
        builder: (BuildContext context) {
          return WillPopScope(
            onWillPop: () async {
              return Future.value(false);
            },
            child: Dialog(
              backgroundColor: Colors.transparent,
              child: GameEndText(
                list: lists,
              ),
            ),
          );
        });
    //获取截图，这里比较耗时。
    WidthUtils().toPng(rootWidgetKey).then((value) {
      //  print("获取到的屏幕是${value}");

      Future.delayed(Duration(milliseconds: 1700), () {
        showDialog(
            context: context,
            // barrierColor: Colors.grey.withOpacity(.4), // Dialog 的背景色
            barrierDismissible: false, //控制 Dialog 是否消失
            barrierLabel: "",
            builder: (BuildContext context) {
              return WillPopScope(
                onWillPop: () async {
                  return Future.value(false);
                },
                child: Dialog(
                  insetPadding: EdgeInsets.only(
                      left: ScreenUtil().setWidth(5),
                      right: ScreenUtil().setWidth(5)),
                  backgroundColor: Colors.transparent,
                  child: GameEndBg(
                    currentScore: CurrentScore,
                    historicalScore: HistoricalScore,
                    gamebg: value,
                    callback: callbacks,
                    type: type,
                  ),
                 
                ),
              );
            });
      });
    });
  }

  /**
   * 旅行完成结束游戏 
   */
  void travelEndGame(
      BuildContext context, int CurrentScore, bool isgem, int grade,
      {List<GemBean>? gemList, CallBack? callbacks}) {
    AudioUtils.getInstance()?.pause();
    int newGrade = grade;
    bool istheme = false;
    int themeCont = 1;
    themeCont = SpUtils.getInstance()!.getInt2(AppConst.theme)!;
    if (newGrade >= 12) {
      //保存本主题徽章
      newGrade = 1;
      istheme = true;
      themeCont = themeCont + 1;
      SpUtils?.getInstance()?.setInt(AppConst.theme, themeCont);
      var badgeBean = BadgeBean();
      badgeBean.time = DateTime.now().millisecondsSinceEpoch;
      badgeBean.img = themeCont > 36
          ? badgeList[badgeList.length - 1]
          : badgeList[themeCont - 1];
      DBManager().insertBadge(badgeBean);
    } else {
      newGrade = newGrade + 1;
    }

    SpUtils.getInstance()?.setInt(AppConst.grade, newGrade);
    showDialog(
        context: context,
        // barrierColor: Colors.grey.withOpacity(.4), // Dialog 的背景色
        barrierDismissible: false, //控制 Dialog 是否消失
        barrierLabel: "",
        builder: (BuildContext context) {
          return WillPopScope(
            onWillPop: () async {
              return Future.value(false);
            },
            child: Dialog(
              insetPadding: EdgeInsets.only(
                  left: ScreenUtil().setWidth(5),
                  right: ScreenUtil().setWidth(5)),
              backgroundColor: Colors.transparent,
              child: TravelGameEnd(
                currentScore: CurrentScore,
                gemList: gemList,
                isgem: isgem,
                grade: newGrade,
                istheme: istheme,
                callback: callbacks,
                themeCont: themeCont,
              ),
            ),
          );
        });

    if (isgem) {
      SpUtils?.getInstance()?.setString(AppConst.travelgemList, "");
      SpUtils?.getInstance()?.setString(AppConst.travelgemCopyList, '');
    }
    //转为json保存
    SpUtils?.getInstance()?.setString(AppConst.trvelContinueGame, '');
    DBManager().deletaHashModelAll(3);
    SpUtils?.getInstance()?.setString(AppConst.travelrandomList, '');
  }

  /**
   * 旅行失败
   */
  void TravelGameFail(BuildContext context, int CurrentScore, bool isgem,
      {List<GemBean>? gemList, CallBack? callbacks}) {
    AudioUtils?.getInstance()?.pause();
    //  print("获取到的屏幕是${value}");
    showDialog(
        context: context,
        // barrierColor: Colors.grey.withOpacity(.4), // Dialog 的背景色
        barrierDismissible: false, //控制 Dialog 是否消失
        barrierLabel: "",
        builder: (BuildContext context) {
          return WillPopScope(
            onWillPop: () async {
              return Future.value(false);
            },
            child: Dialog(
              insetPadding: EdgeInsets.only(
                  left: ScreenUtil().setWidth(5),
                  right: ScreenUtil().setWidth(5)),
              backgroundColor: Colors.transparent,
              child: TravelGameFile(
                currentScore: CurrentScore,
                callback: callbacks,
                gemList: gemList,
                isgem: isgem,
              ),
            ),
          );
        });

    if (isgem) {
      SpUtils?.getInstance()?.setString(AppConst.travelgemList, "");
      SpUtils?.getInstance()?.setString(AppConst.travelgemCopyList, '');
    }
    //转为json保存
    SpUtils?.getInstance()?.setString(AppConst.trvelContinueGame, '');
    DBManager().deletaHashModelAll(3);
    SpUtils?.getInstance()?.setString(AppConst.travelrandomList, '');

    AudioUtils.getInstance()?.play2("classic_ordinary.mp3");
  }

  /**
   * 挑战失败
   */
  void GameFail(
      BuildContext context, int CurrentScore, GlobalKey rootWidgetKey, int type,
      {CallBack? callbacks}) {
    List<String> lists = [];
    AudioUtils?.getInstance()?.pause();
    if (type == 2) {
      lists.add(S.of(context).no_spaces_left);
      //成功完成游戏每日挑战
      SpUtils?.getInstance()?.setInt(AppConst.everyDayContinueScore, 0);
      SpUtils?.getInstance()?.setString(AppConst.everyDayrandomList, "");
      SpUtils.getInstance()!.setString(AppConst.everyDayContinueGame, "");
      SpUtils.getInstance()?.setBool(AppConst.complete, false);
      SpUtils.getInstance()?.setInt(
          AppConst.completeTime, DateTime.now().millisecondsSinceEpoch);
    }

    DBManager().deletaHashModelAll(type);

    print("挑战失败");

    showDialog(
        context: context,
        // barrierColor: Colors.grey.withOpacity(.4), // Dialog 的背景色
        barrierDismissible: false, //控制 Dialog 是否消失
        barrierLabel: "",
        builder: (BuildContext context) {
          return WillPopScope(
            onWillPop: () async {
              return Future.value(false);
            },
            child: Dialog(
              backgroundColor: Colors.transparent,
              child: GameEndText(
                list: lists,
              ),
            ),
          );
        });

    //获取截图，这里比较耗时。
    WidthUtils().toPng(rootWidgetKey).then((value) {
      //  print("获取到的屏幕是${value}");

      Future.delayed(Duration(milliseconds: 1700), () {
        showDialog(
            context: context,
            // barrierColor: Colors.grey.withOpacity(.4), // Dialog 的背景色
            barrierDismissible: false, //控制 Dialog 是否消失
            barrierLabel: "",
            builder: (BuildContext context) {
              return WillPopScope(
                onWillPop: () async {
                  return Future.value(false);
                },
                child: Dialog(
                  insetPadding: EdgeInsets.only(
                      left: ScreenUtil().setWidth(5),
                      right: ScreenUtil().setWidth(5)),
                  backgroundColor: Colors.transparent,
                  child: GameFileText(
                    currentScore: CurrentScore,
                    gamebg: value,
                    callback: callbacks,
                    type: type,
                  ),
                ),
              );
            });
        AudioUtils.getInstance()?.play2("classic_ordinary.mp3");
      });
    });
  }

/**
 * 每日挑战 今天是否完成 true完成 iscontinue=true 挑战游戏界面，false时用于我的和每日界面
 */
  bool challengeComplete(bool iscontinue) {
    AudioUtils?.getInstance()?.pause();
    bool? complete = SpUtils.getInstance()?.getBool(AppConst.complete);
    int? completeTime = SpUtils.getInstance()?.getInt(AppConst.completeTime);

    if (complete != null && completeTime != null) {
      if (TimeUtils.gtTime(DateTime.now()) ==
          TimeUtils.gtTime(DateTime.fromMillisecondsSinceEpoch(completeTime))) {
        //同一天
        if (!iscontinue) {
          //用于我的界面
          if (complete) {
            //完成了
            return true;
          } else {
            //没完成
            return false;
          }
        } else {
          //在同一天 继续游戏
          return true;
        }
      } else {
        //不同一天了
        SpUtils.getInstance()?.setBool(AppConst.complete, false);
        SpUtils.getInstance()?.setInt(
            AppConst.completeTime, DateTime.now().millisecondsSinceEpoch);

        return false;
      }
    } else {
      SpUtils.getInstance()?.setBool(AppConst.complete, false);
      SpUtils.getInstance()?.setInt(
          AppConst.completeTime, DateTime.now().millisecondsSinceEpoch);
      // return getcomplete();
      return false;
    }
  }

  void sucessComplete() {}
}
